﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using LibrarySystem.LibraryUtils.Entities;
using System.Web.Security;

namespace LibrarySystem.LibraryUtils.DAL.DAOs
{
    public class Common
    {

        protected LibraryEntitiesDataContext GetDataContext()
        {
            return new LibraryEntitiesDataContext();
        }

        public int GetStudentIdByUsername(string username)
        {
            LibraryEntitiesDataContext _context = GetDataContext();
            //Code
            var query = _context.Library_Students.Where(s => s.aspnet_User.UserName == username);
            Library_Student student = query.First<Library_Student>();
            //
            _context.Dispose();
            return student.Id;
        }

        public int GetEmployeeIdByUsername(string username)
        {
            LibraryEntitiesDataContext _context = GetDataContext();
            //Code
            var query = _context.Library_Employees.Where(s => s.aspnet_User.UserName == username);
            Library_Employee employee = query.First<Library_Employee>();
            //
            _context.Dispose();
            return employee.Id;
        }

        protected Guid CreateUserAccount(string username, string password, string roles, string email = null)
        {
            LibraryEntitiesDataContext _context = GetDataContext();
            MembershipUser mUser;

            if (string.IsNullOrEmpty(email))
                mUser = Membership.CreateUser(username, password);
            else
                mUser = Membership.CreateUser(username, password, email);

            aspnet_User user = _context.aspnet_Users.Where(u => u.UserName == mUser.UserName).First<aspnet_User>();
            aspnet_UsersInRole uir = new aspnet_UsersInRole();

            uir.RoleId = _context.aspnet_Roles.Where(r => r.RoleName == roles).First<aspnet_Role>().RoleId;
            uir.UserId = user.UserId;
            _context.aspnet_UsersInRoles.InsertOnSubmit(uir);
            _context.SubmitChanges();
            //
            _context.Dispose();
            return user.UserId;
        }
    }
}